﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using log4net;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Reflection;

namespace PreCommitHook
{
    /// <summary>
    /// 
    /// </summary>
    public class EmailNotifier
    {
        static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static void SendEmail(string bodyData)
        {
            MailMessage message = new MailMessage();

            foreach (string recipient in GetRecipients())
            {
                message.To.Add(new MailAddress(recipient));           
            }        
            message.Subject = "svn pre-commit hook";
            message.Body = bodyData;
            SmtpClient client = new SmtpClient();

            try
            {
                client.Send(message);
            }
            catch (SmtpException ex)
            {
                log.Fatal("Sending email failed with SMTP exception", ex);
                throw ex;
            }
            catch (Exception ex)
            {
                log.Fatal("Sending email failed with exception", ex);
                throw ex;
            }

        }

        #region helpers
        public static List<String> GetRecipients()
        {
            List<String> recipients = new List<String>();
            try
            {
                string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                XDocument xDoc = XDocument.Load(path + @"\Config\emails.xml");
                var query = (from el in xDoc.Root.Elements()
                             where el.Name.LocalName.Equals("recipient")
                             select el.Value);

                recipients = query.ToList<String>();
            }
            catch (XmlException ex)
            {
                log.Fatal("XmlException on getting recipients with email.xml", ex);
                throw ex;
            }
            catch (Exception ex)
            {
                log.Fatal("Exception on getting recipients with email.xml", ex);
                throw ex;
                
            }
            return recipients;
        }
        #endregion
    }
}
